# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from django.contrib.sessions.backends.db import SessionStore
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from main.models import Rest, Rest_dish
from order.models import Dish_cart, Dish_cart_item, Order
from pub import utils
from space.views import rest

def add_to_cart(request):
    result = {}
    if request.method == 'POST':
        restid = request.POST.get("restid")
        dishid = request.POST.get("dishid")
        '''
        '若为此餐厅的第一道菜，则先新建一个菜单,再添加菜式'''
        dc =_get_user_cart(request) 
        di = None
        try:
            di = dc.dish_cart_item_set.get(rest_dish__pk=dishid)
        except:
            pass
        if di == None:
            d = Rest_dish.objects.get(pk=dishid)
            di = Dish_cart_item(dish_cart=dc,rest_dish=d,name=d.name, price=d.price, amount=1) 
            di.save()
            dc.dish_cart_item_set.add( di )
        else:
            di.amount = (di.amount + 1) 
            di.save()
        result = {"restid":restid, "dish_item":di, "cartid":dc.id}
    return HttpResponse(result, mimetype="text/plain")
def _get_user_cart(request):
    '''系统为点餐的用户开单，如果已经点过菜，就直接返回菜单;
                  如果是以前从来没点过菜的，就新创建一个菜单'''
    user = request.user
    session_key = request.session.session_key
    restid = request.POST.get("restid")
    try:
        dcq = Dish_cart.objects.filter(rest__pk=restid, state=False)
        if user.is_authenticated():
            dc = dcq.filter(user__pk=user.id )[0]
        else:
            dc = dcq.filter(session__pk=session_key)[0]
    except:
        rest = Rest.objects.get(pk=restid)
        if user.is_authenticated():
            u = User.objects.get( pk = user.id )
            dc = Dish_cart(rest=rest, user=u, state=False)
        else:
            try:
                s = Session.objects.get(pk = session_key)
            except:
                s = SessionStore(session_key=session_key)
                s.save()
            dc = Dish_cart(rest=rest, session=s,state=False)
        dc.save();
    return dc

def del_from_cart(request):
    if request.method == 'POST':
        dishid = request.POST.get("dishid")
        
@login_required
def place_order(request,template_name="order_place.html", pk=None):
    if request.method == 'GET':
        cart = Dish_cart.objects.get( pk = pk )
        return render_to_response(template_name,{"cart":cart},context_instance=RequestContext(request))
    else:
        #提交订单
        cart = Dish_cart.objects.get( pk = pk )
        u = User.objects.get( pk = request.user.id )
        pwd = "2a3sd"
        order = Order(dish_cart=cart ,rest= cart.rest ,user=u, pwd=pwd, total= cart.get_total())
        order.save()
        cart.state = True
        cart.save()
        utils.send_sms(u.username,"订餐成功")
        rest_msg = "用户:%s在你的网上餐厅订餐，请注意查收" % u.username
        utils.send_sms(cart.rest.user.username,rest_msg)
        return HttpResponseRedirect( reverse('customer_order') )
